package Controllers;

import java.awt.event.ActionEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import Boundry.NominateExaminerGUI;
import Boundry.ReviewAndDecisionGUI;
import Boundry.Waiting;
import Boundry.GenericTools.RequestTableListPanel;
import Controllers.GenericToolsForController.BaseClass;
import Controllers.GenericToolsForController.PDFDocument;
import Controllers.GenericToolsForController.PDFfile;
import Controllers.GenericToolsForController.RequestMainStatusEnum;
import Controllers.GenericToolsForController.RequestStepStatusEnum;
import Controllers.GenericToolsForController.WorkerPostion;
import Entity.Request;
import Entity.Status;
import Entity.Worker;
/**
 * 
 * @author Group16
 *
 */

public class ChairmanController extends BaseClass
{
	/*
	 * Singleton 
	 */
	private NominateExaminerGUI _NominateExaminerGUI;
	private RequestTableListPanel ListofAllREquestsToBeAsigened;
	
	private ReviewAndDecisionGUI _ReviewAndDecisionGUI;            // for review and decision step
	private RequestTableListPanel ListofAllRequestsToBeReviewed;

	private static  ChairmanController Instance = null;
	
	int reqid_chosed;
	private Request chosenRequest;
	
	private ArrayList<Request> reqsToReviewChairMan ;
	private ArrayList<Request> reqsToAssignExaminer ;
	private Waiting waitScreen;
	
	/**
	 * 
	 * empty constructor 
	 * 
	 * 
	 */
	private ChairmanController(){}
	
	 /**
	  *  Singleton - getInstance method
	  * @return
	  */

	public static ChairmanController getInstance()
	{
		if(Instance == null)
		{
			Instance = new ChairmanController();
		}
		return Instance;
	}
/*
 *  review request method
 *  using SwingWorker we built the GUI panel for the query which returns All the Requests To Be Reviewed
 *  in the viewDataPanel.  
 *  
 */
	public void reviewRequest()
	{
		waitScreen = new Waiting();
		SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
			@Override
			 public Void doInBackground() 
			 {		
				
				reqsToReviewChairMan = (ArrayList<Request>) RequestManager.getInstance().getAllRequestsToBeReviewed(GlobalData.worker);
				
				
				//Build table for the reviewed request list.
				if(reqsToReviewChairMan.size()>0)
				{
					tableData =  new String[reqsToReviewChairMan.size()][reqsToReviewChairMan.get(0).dataToStringArray().length];
					for(int i=0; i<tableData.length ; i++)
					{
						tableData[i] = reqsToReviewChairMan.get(i).dataToStringArray();
					}
					columnNames = reqsToReviewChairMan.get(0).indexStringArray();
					ListofAllRequestsToBeReviewed = new RequestTableListPanel();
					GlobalData.guiMangaer.switchScreen(ListofAllRequestsToBeReviewed);
					ListofAllRequestsToBeReviewed.buildTabel(columnNames,tableData);
					setListenerToViewDataPanel(ListofAllRequestsToBeReviewed);	
				}
				else
				{
					waitScreen.kill();
					JOptionPane.showMessageDialog(new JFrame(),"There is not request that can be reviewed", "",JOptionPane.DEFAULT_OPTION);
				}
				return null;
			 	}
				@Override
				public void done() 
				{
					waitScreen.kill();
					waitScreen=null;
				}
			    };
			    worker.execute();
	}
	/**
	 * moreDetailsNeeded method change the status of the chosen request to the status RequestStepStatusEnum.EVL_RETURNED_TO_REVALUTION
	 * and update the history of the request
	 */
	public void moreDetailsNeeded(){
		
		chosenRequest.changeStatus(new Status(RequestStepStatusEnum.EVL_RETURNED_TO_REVALUTION, RequestMainStatusEnum.OPEN), "Review And Decision Needs More info ",chosenRequest.getTimeForEvaluation());
		
	}
	/**
	 *  denyRequest method change the status of the chosen request to RequestStepStatusEnum.REV_REVIEWED_CLOSE
	 *  and update the history of the request 
	 */
	public void denyRequest()
	{
		chosenRequest.changeStatus(new Status(RequestStepStatusEnum.REV_REVIEWED_CLOSE, RequestMainStatusEnum.OPEN), "Review And Decision Denied ",0);
	}
	/**
	 * approveRequest method change the status of the chosen request to RequestStepStatusEnum.REV_REVIEWED_PASSED
	 * and update the history of the request  
	 */
	public void approveRequest()
		{
		chosenRequest.changeStatus(new Status(RequestStepStatusEnum.REV_REVIEWED_PASSED, RequestMainStatusEnum.OPEN), "Review And Decision approved ",chosenRequest.getTimetimeForExecution());
		}
	/**
	 *  assign examiner to request method calls all the proper methods and building gui panel to display
	 *  the query of All Requests Without Examiner
	 */
	public void AssignExaminerToRequest(){
		/*
		 * build the list of what we want to show in the table
		 * String[] columnNames = { "Request Id", "Date of Finish", "status", "Command" };
		 * 
		 */
	
		reqsToAssignExaminer = (ArrayList<Request>) RequestManager.getInstance().getAllRequestsWithoutExaminer(GlobalData.worker.getId(),WorkerPostion.CHAIR_MEN,new Status[]{new Status(RequestStepStatusEnum.NOMINATED,RequestMainStatusEnum.OPEN)});
		
		String[] columnNames = { "Request Id", "Date of Finish", "status", "Command" };
		String[][] tableData =  {{}};
		
		if(reqsToAssignExaminer.size() <= 0)
		{
			JOptionPane.showMessageDialog(new JFrame(),"There Is Not Request That Can Be Assigned", "",JOptionPane.DEFAULT_OPTION);
			GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
		}
		else
		{
			ListofAllREquestsToBeAsigened = new RequestTableListPanel();
			GlobalData.guiMangaer.switchScreen(ListofAllREquestsToBeAsigened);
			
			setListenerToViewDataPanel(ListofAllREquestsToBeAsigened);	
			
			tableData =  new String[reqsToAssignExaminer.size()][reqsToAssignExaminer.get(0).dataToStringArray().length];
			for(int i=0; i<tableData.length ; i++)
			{
				tableData[i] = reqsToAssignExaminer.get(i).dataToStringArray();
				System.out.println(reqsToAssignExaminer.get(i).getRequestId()+" \n");
			}
			columnNames = reqsToAssignExaminer.get(0).indexStringArray();
			ListofAllREquestsToBeAsigened.buildTabel(columnNames,tableData);
		
		}
		
		
	}
	@Override
	/*
	 * (non-Javadoc)
	 * @see Controllers.GenericToolsForController.BaseClass#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		
		/*
		 * NominateExaminerListener  Handle Listener
		 */
		NominateExaminerListener(e);
		
		/*
		 * ReviewAndDecisionListener  Handle Listener
		 */
		ReviewAndDecisionListener(e);
		
		
	}
	/**
	 *  method for handling click event instead nominate examiner
	 * @param e event handler
	 */
	private void NominateExaminerListener(ActionEvent e) {
		if (ListofAllREquestsToBeAsigened!=null){
			if (e.getSource() == ListofAllREquestsToBeAsigened.btnBack)
			{	
				GUIControllerWorker.getInstance().inizializtion();
			}
			else if (e.getSource() == ListofAllREquestsToBeAsigened.btnNext)
			{	
				if(ListofAllREquestsToBeAsigened.isChosen())
				{
					_NominateExaminerGUI =  new NominateExaminerGUI();
					
					
					setListenerToInputPanel(_NominateExaminerGUI);
					SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
						@Override
						 public Void doInBackground() 
						 {
							System.out.println("entry point ");
							ArrayList<Worker> workerlist;
							int reqid = ListofAllREquestsToBeAsigened.getChosen();
							Request reqChoosen = reqsToAssignExaminer.get(reqid);
							reqid_chosed = reqChoosen.getRequestId();
								// worker.dataToStringArray();
								_NominateExaminerGUI.addElementToComboBox(""+reqChoosen.getChairman().getId() +") "+reqChoosen.getChairman().getFirstName() +" " +reqChoosen.getChairman().getLastName());
								_NominateExaminerGUI.addElementToComboBox(""+reqChoosen.getCometteMembers1().getId() +") "+reqChoosen.getCometteMembers1().getFirstName() +" " +reqChoosen.getCometteMembers1().getLastName());
								_NominateExaminerGUI.addElementToComboBox(""+reqChoosen.getCometteMembers2().getId() +") "+reqChoosen.getCometteMembers2().getFirstName() +" " +reqChoosen.getCometteMembers2().getLastName());
								//System.out.println(tableData[i][0]  +  tableData[i][1]);
							
						//	_NominateExaminerGUI.setdata(ListofAllREquestsToBeAsigened.getChosen() + "");
							return null;
							
							
						 }
						@Override
							public void done(){
								GlobalData.guiMangaer.switchScreen(_NominateExaminerGUI);
								//AssignExaminerToRequest();
							}
					};	
					worker.execute();
				}
				else
				{
					//user not coohse request 
				}
				
			}
			else if (e.getSource() ==_NominateExaminerGUI.btnBack ){
				GlobalData.guiMangaer.switchScreen(ListofAllREquestsToBeAsigened);
			}
			else if (e.getSource() ==_NominateExaminerGUI.btnSubnit){
			String id  = (String) _NominateExaminerGUI.getcomboBoxWorker().getSelectedItem();
			String[] ids = id.split("\\)");
			
				RequestManager.getInstance().assignExaminer(ids[0],reqid_chosed);
				AssignExaminerToRequest();
				//GlobalData.guiMangaer.switchScreen(ListofAllREquestsToBeAsigened);
				//GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			}	
		
	}
	/**
	 *  listener for review and decision
	 * @param e action handler
	 */
	private void ReviewAndDecisionListener(ActionEvent e) {	
		if (ListofAllRequestsToBeReviewed!=null)
		{
			if (e.getSource() == ListofAllRequestsToBeReviewed.btnBack)
			{	
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == ListofAllRequestsToBeReviewed.btnNext)
			{	
				if(ListofAllRequestsToBeReviewed.isChosen())
				{
					_ReviewAndDecisionGUI =  new ReviewAndDecisionGUI();
					chosenRequest = reqsToReviewChairMan.get(ListofAllRequestsToBeReviewed.getChosen());
					_ReviewAndDecisionGUI.setTxtCreationDate(chosenRequest.getDayOfCreation());
					_ReviewAndDecisionGUI.setTxtDescription(chosenRequest.getDescription());
					_ReviewAndDecisionGUI.setTxtExcuse(chosenRequest.getExecuse());
					_ReviewAndDecisionGUI.setTxtInfoSystem(chosenRequest.getInfoSystem().toString());
					_ReviewAndDecisionGUI.setTxtInitiator(chosenRequest.getInitiator().toString());
					_ReviewAndDecisionGUI.setTxtNotes(chosenRequest.getNotes());
					_ReviewAndDecisionGUI.setTxtPropChange(chosenRequest.getProposedChange());
					_ReviewAndDecisionGUI.getBtnViewEVAReport().addActionListener(this);
					_ReviewAndDecisionGUI.getRdbtnApprove().addActionListener(this);
					_ReviewAndDecisionGUI.getRdbtnDeny().addActionListener(this);
					_ReviewAndDecisionGUI.getRdbtnNeedsMoreInformation().addActionListener(this);
					setListenerToInputPanel(_ReviewAndDecisionGUI);
					
					SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() 
						{
							@Override
							 public Void doInBackground() 
							 {
								return null;
							 }
							@Override
							public void done()
							{
								GlobalData.guiMangaer.switchScreen(_ReviewAndDecisionGUI);
							}
							};	
							worker.execute();
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),"Please select request from the list" ,"Error",JOptionPane.ERROR_MESSAGE);	
				}
			}
			else if (e.getSource() == ListofAllRequestsToBeReviewed.btnRefresh)
			{	
					//ListofAllRequestsToBeReviewed.removeRow(0);	
			}	
		}
		if (_ReviewAndDecisionGUI != null )
		{
			if (e.getSource() == _ReviewAndDecisionGUI.btnAskForMoreTime)
			 {	 	
				 this.askForMoreTime(chosenRequest);
			 }
			
			else if (e.getSource() ==_ReviewAndDecisionGUI.btnBack )
			{
					GlobalData.guiMangaer.switchScreen(ListofAllRequestsToBeReviewed);
			}
			else if (e.getSource() ==_ReviewAndDecisionGUI.btnSubnit)
			{
						if (_ReviewAndDecisionGUI.getRdbtnDeny().isSelected())
						{
									this.denyRequest();
									JOptionPane.showMessageDialog(new JFrame(),"Request number "+chosenRequest.getRequestId() +" was denied!!","Notice",JOptionPane.INFORMATION_MESSAGE);
									GUIControllerWorker.getInstance().inizializtion();
						}
						else if (_ReviewAndDecisionGUI.getRdbtnApprove().isSelected())
						{
									this.approveRequest();
									JOptionPane.showMessageDialog(new JFrame(),"Request number "+chosenRequest.getRequestId() +" was appoved!!","Notice",JOptionPane.INFORMATION_MESSAGE);
									GUIControllerWorker.getInstance().inizializtion();
						}
						else if (_ReviewAndDecisionGUI.getRdbtnNeedsMoreInformation().isSelected())
						{
									this.moreDetailsNeeded();						
									JOptionPane.showMessageDialog(new JFrame(),"Request number "+chosenRequest.getRequestId() +" needs More Information!!\nthis request return to evaluation step!!","Notice",JOptionPane.INFORMATION_MESSAGE);
									 //TODO adding text description of the extra details needed
									GUIControllerWorker.getInstance().inizializtion();						   
						}  
						else   //in case user press submit without having any decision 				
						{
									JOptionPane.showMessageDialog(new JFrame(),"Please choose the commettee decision in the frame below!!","Error",JOptionPane.ERROR_MESSAGE);
									_ReviewAndDecisionGUI.getStep3Pane().setVisible(true);
									//GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
						}
			 }
			 if(e.getSource() == _ReviewAndDecisionGUI.getBtnViewEVAReport())
			{   
					PDFfile file = chosenRequest.getEvaluationReport().getPdfFile();
					if(file!=null)
					{
						new PDFDocument(file, "DateFileFromReq" + chosenRequest.getRequestId());
					}
					else
					{
						JOptionPane.showMessageDialog(new JFrame(),"There is no Evaluation report File for this request","Error",JOptionPane.ERROR_MESSAGE);
					}
					_ReviewAndDecisionGUI.getStep3Pane().setVisible(true);
			}
			 if(e.getSource() == _ReviewAndDecisionGUI.getRdbtnApprove())
				{   
				 _ReviewAndDecisionGUI.getRdbtnApprove().setSelected(true);
				 _ReviewAndDecisionGUI.getRdbtnDeny().setSelected(false);
				 _ReviewAndDecisionGUI.getRdbtnNeedsMoreInformation().setSelected(false);
				 _ReviewAndDecisionGUI.getTxtpnMoreinfo().setVisible(false);
				}
		    else if (e.getSource() == _ReviewAndDecisionGUI.getRdbtnDeny())
			 {
				 _ReviewAndDecisionGUI.getRdbtnApprove().setSelected(false);
				 _ReviewAndDecisionGUI.getRdbtnDeny().setSelected(true);
				 _ReviewAndDecisionGUI.getRdbtnNeedsMoreInformation().setSelected(false);
				 _ReviewAndDecisionGUI.getTxtpnMoreinfo().setVisible(false); 
			 }
			 else if (e.getSource() == _ReviewAndDecisionGUI.getRdbtnNeedsMoreInformation())
			 {
				 _ReviewAndDecisionGUI.getRdbtnNeedsMoreInformation().setSelected(true);
				 _ReviewAndDecisionGUI.getTxtpnMoreinfo().setVisible(true);
				 _ReviewAndDecisionGUI.getRdbtnApprove().setSelected(false);
				 _ReviewAndDecisionGUI.getRdbtnDeny().setSelected(false);				 
			 }
		}	
	}
}

